package com.zj.study.config;

import com.zj.study.autoconfig.WebAutoConfiguration;
import com.zj.study.service.impl.UserServiceImpl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;

/**
 * @author 赵赳
 * @since 2021/12/13 10:00
 */
@Configuration
public class MyBeanPostProcessor implements BeanPostProcessor {

  @Override
  public Object postProcessBeforeInitialization(Object bean, String beanName)
      throws BeansException {
    Class<?> beanClass = bean.getClass();
    if (beanClass == UserServiceImpl.class) {
      System.out.println("bean 对象初始化之前······");
    }
    return bean;
  }

  @Override
  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    // 为当前 bean 对象注册监控代理对象，负责增强 bean 对象方法的能力
    Class<?> beanClass = bean.getClass();
    if (beanClass == UserServiceImpl.class) {
      return Proxy
          .newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(),
              (proxy1, method, args) -> {
                System.out.println("ISomeService 中的 doSome() 被拦截了···");
                return method.invoke(bean, args);
              });
    }
    return bean;
  }
}
